﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="pgGeoreferencia.aspx.cs" Inherits="EGuayas.Web.Expedientes.pgGeoreferencia" %>
<%@ Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link  href="~/Resources/css/Style.css"  rel="stylesheet" />
    <!-- Load Ext JS --> 
    <script src="../Resources/js/Global.js"></script>
    <script type="text/javascript" src="../Resources/js/urm2lat.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> 
</head>
<body>
      <ext:ResourceManager ID="ResourceManager1" runat="server" />
      <ext:Viewport ID="ViewportGeo" runat="server" Layout="BorderLayout">
            <Items>
                   <ext:Hidden Text="" ID="hdIdPage"  runat="server" />
                   <%--  Almacena el valor de expediente en panel de puntos de referencia  --%>
                   <ext:Hidden Text="" ID="hdExpGeo"  runat="server" />
                   <%--  Identifica si se invoco metodos desde aspx pgNuevoExpediente  --%>
                   <ext:Hidden Text="false" ID="hdIfCreateExp"  runat="server" />
                   <ext:GridPanel ID="gpPoinst" 
                            runat="server" 
                            BodyStyle="background-color: rgb(236, 236, 236)"                           
                            ButtonAlign="Center"
                            Region="West"  
                            Flex="1"
                            Margins ="15"                     
                            BodyPadding="10"
                            LabelWidth="100">                     
                            <TopBar>
                                    <ext:Toolbar ID="Toolbar1" runat="server">
                                        <Items>
                                            <ext:Button ID="btnAdd" runat="server" Text="Agregar Referencia"  Icon="MapAdd">
                                                <Listeners>
                                                    <Click Fn="pgFn.addBtnPoint" />
                                                </Listeners>
                                            </ext:Button>
                                              <ext:Button ID="btnAddUpdate" runat="server" Text="Agregar Referencia"  Icon="MapEdit" Hidden="true">
                                                <Listeners>
                                                    <Click Fn="pgFn.addBtnPointUdate" />
                                                </Listeners>
                                            </ext:Button>
                                           <ext:Button ID="btnRemove" runat="server" Text="Eliminar Refrencia"   Disabled ="true" Icon="MapDelete">
                                                <Listeners>
                                                    <Click Fn="pgFn.deleteBtnPoint " />
                                                </Listeners>
                                            </ext:Button>
                                        </Items>
                                    </ext:Toolbar>
                                </TopBar>       
                            <Store>
                                <ext:Store 
                                    ID="stoRef" 
                                    runat="server">
                                    <Model>
                                        <ext:Model ID="Model1" runat="server" Name="XY">
                                            <Fields>
                                                <ext:ModelField Name="Latitud"  />
                                                <ext:ModelField Name="Longitud"   />
                                                <ext:ModelField Name="Id"  />
                                                <ext:ModelField Name="ExpedienteId"   />
                                                <ext:ModelField Name="Orden"  />
                                                <ext:ModelField Name="Tipo"  />
                                             </Fields>
                                        </ext:Model>
                                    </Model>
                                   
                                </ext:Store>
                                
                            </Store>
                            <Plugins>
                                    <ext:RowEditing ID="RowEditing" runat="server" ClicksToMoveEditor="1" AutoCancel="true"
                                        SaveHandler="pgFn.clickBtnAgregar(this.editingPlugin);"
                                        SaveBtnText="Aceptar">
                                    <Listeners>
                                     
                                       <CancelEdit Handler="pgFn.beforeEditRow(item,e);"/>
                                    </Listeners>
                                    </ext:RowEditing>
                            </Plugins> 
                            <ColumnModel ID="ColumnModel1" runat="server">
                                <Columns>
                                    <ext:Column ID="Column1" runat="server" DataIndex="Latitud" Text="X"  Flex="1">  
                                        <Editor>
                                         <ext:NumberField ID="NumberField1"  DecimalSeparator="." 
                                            runat="server" AllowBlank="false" />
                                        </Editor>
                                    </ext:Column>

                                    <ext:Column ID="Column2" runat="server" DataIndex="Longitud" Text="Y"  Flex="1">  
                                        <Editor>
                                         <ext:NumberField ID="NumberField2" DecimalSeparator="."  
                                            runat="server" AllowBlank="false" />
                                    </Editor>
                                    </ext:Column>
                                    <ext:NumberColumn runat="server" Width="17"></ext:NumberColumn>
                                     <%-- 
                                      <ext:ImageCommandColumn ID="ImageCommandColumn1" runat="server" Flex="1" Sortable="false">
                                            <Commands>
                                                <ext:ImageCommand Icon="Decline" ToolTip-Text="Eliminar Punto de Referencia" CommandName="delete">                            
                                                </ext:ImageCommand>
                                            </Commands>
                                            <Listeners>
                                                <Command Handler="pgFn.clickBtnDelete(record,recordIndex);" />
                                            </Listeners>
                                        </ext:ImageCommandColumn>
                                        --%>
                                </Columns>
                            </ColumnModel>
                            <View>
                                <ext:GridView ID="GridView1" runat="server">
                                    <Plugins>
                                        <ext:GridDragDrop ID="GridDragDrop1" runat="server" DragText="Reorganizar puntos de referencia" >   
                                                                     
                                        </ext:GridDragDrop>                                
                                    </Plugins>
                                    <Listeners>                              
                                        <BeforeDrop  Handler="pgFn.setPointPaint();"/>
                                    </Listeners>
                                </ext:GridView>
                            </View>
                            <Buttons>
                                
                                 <ext:Button runat="server" ID="btnFlag"  Disabled="true" Hidden="true">  
                                 </ext:Button>
                            </Buttons>
                           <Listeners>
                                 <SelectionChange Handler="pgFn.selectRowPoint(item,selected);" />
                          </Listeners>
                        </ext:GridPanel>
                   <ext:FormPanel 
                            ID="frpMap" 
                            runat="server" 
                            Region="Center"
                            Split="true"
                            Margins="0 5 5 5"
                            BodyPadding="2"                  
                            Title="Mapa" 
                            
                            Flex="1"
                            Html="<div id='map-canvas' style='padding: 0px; width: 100%; height: 100%; left: 0px; top: 0px;'></div><div id='main-frame-error' style='padding: 0px; width: 100%; height: 100%; left: 0px; top: 0px;'><div id='box'><div class='read1'><div class='read1-img1'><img width='32' height='30' alt='img' src=''></div><center><h3>Sin recursos de red</h3></center><p></p></div></div></div>"
                            Icon="Map">
                            <Items></Items>
                    
                            <Listeners>
                                <AfterRender Handler=" if(pgFn.render==false){ pgFn.newMap(null);pgFn.render=true;}" />
                            </Listeners>
                             <BottomBar>
                                    <ext:Toolbar ID="Toolbar2" runat="server">
                                        <Items>
                                            <ext:ToolbarFill ID="ToolbarFill1" runat="server" />
                                            <%-- 
                                            <ext:Button ID="Button2" runat="server" Text="Limpiar" Icon="MapDelete">
                                                <Listeners>
                                                    <Click Handler=" pgFn.resetMap();" />
                                                </Listeners>
                                            </ext:Button>
                                                 --%>
                                        </Items>
                                    </ext:Toolbar>
                         </BottomBar>
                        </ext:FormPanel>
                   <ext:Panel runat="server" Region="South" Border="false"  ButtonAlign="Center"   Margins="10 5 5 10">
                        <Buttons>
                             <ext:Button runat="server" ID="btnSave" Text="Confirmar puntos de referencia" Disabled="true"  Icon="MapGo" >           
											 <DirectEvents>
													<Click OnEvent="btnGuardar_Click" >
														<EventMask ShowMask="true" />
														<ExtraParams>
															  <ext:Parameter Name="GridData" Value="Ext.encode(#{gpPoinst}.getRowsValues({selectedOnly : false}))" Mode="Raw" />
                                                              <ext:Parameter Name="IfAddExp" Value="#{hdIfCreateExp}.getValue()" Mode="Raw" />														  
														</ExtraParams>
													</Click>
											 </DirectEvents>
                            </ext:Button>
                        </Buttons>
                   </ext:Panel> 
            </Items>
             
           
        </ext:Viewport>
    
        <ext:XScript ID="XScript1" runat="server">
            <script  type="text/javascript">
                //<Click Handler="GridPanel1.getStore().add(new GridPanel1.store.recordType({ test1: 'new 1', test2: 'new 2', test3: 'new 3' }));" />
                if (typeof(google)!="undefined")
                {
                    google.maps.Map.prototype.markers = new Array();
                    google.maps.Map.prototype.addMarker = function (marker) 
                    {
                        this.markers[this.markers.length] = marker;
                    };              
                    google.maps.Map.prototype.getMarkers = function () {
                        return this.markers
                    };               
                    google.maps.Map.prototype.clearMarkers = function () {
                        for (var i = 0; i < this.markers.length; i++) {
                            this.markers[i].setMap(null);
                        }
                        this.markers = new Array();
                    }; 
                    /** @this {google.maps.Polygon} */
                    function createPolygon() {

                 
                        var pointCoords = [];
                        var pointBegin  = null;
                        for (var indice in pgFn.poinstCoords) {
                            var ifAdd=true;
                            var item=pgFn.poinstCoords[indice];
                            //
                            var latlon = new Array(2);
                            //UTMXYToLatLon (x, y, zone, southhemi, latlon);
                            UTMXYToLatLon (item.Latitud,item.Longitud,pgFn.Zone, pgFn.HemSur, latlon);
                            var valLon = RadToDeg (latlon[1]);
                            var valLat = RadToDeg (latlon[0]);
                            var xy  =new google.maps.LatLng(valLat,valLon);
                            if (indice== 0)
                            {
                                pointBegin=xy;
                                pgFn.newMap(xy);
                            }
                            pointCoords.push(xy);
                            var marker = new google.maps.Marker({
                                position:xy
                           
                            })
                            if (pgFn.myLatLng!=null)
                            {
                                if(pgFn.myLatLng.getPosition().equals(marker.getPosition()))
                                    ifAdd=false;
                                else
                                    ifAdd=true;
                            }
                            if(ifAdd)
                                marker = new google.maps.Marker({
                                    position:xy,
                                    map: pgFn.map
                                });
                        }
                        if (pgFn.myLatLng!=null)
                        {
                            var marker = new google.maps.Marker({
                                position:pgFn.myLatLng.getPosition(),
                                map: pgFn.map,
                                icon: 'blue-dot.png'
                            });
                        }
                        if (pointBegin  != null && pgFn.poinstCoords.length!= 1)
                            pointCoords.push(pointBegin);
                        if (pgFn.map == null)
                            pgFn.newMap(null);

                  
                        //google.maps.Map.addMarker(marker);
                        if (pointCoords.length >= 3) {
                            /*
                            var bermudaTriangle;
                            bermudaTriangle = new google.maps.Polygon({
                                paths: pointCoords,
                                strokeColor: '#FF0000',
                                strokeOpacity: 0.8,
                                strokeWeight: 3,
                                fillColor: '#FF0000',
                                fillOpacity: 0.35
                            });
    
                            bermudaTriangle.setMap(pgFn.map);
    
                            // Add a listener for the click event
                            google.maps.event.addListener(bermudaTriangle, 'click', showArrays);
                            infoWindow = new google.maps.InfoWindow();
                            */
                            var flightPath = new google.maps.Polyline({
                                path: pointCoords,
                                strokeColor: '#FF0600',
                                strokeOpacity: 1.0,
                                strokeWeight: 2
                            });

                            flightPath.setMap(pgFn.map);
                        }
                   
                    }
                    /** @this {google.maps.Polygon} */
                    function showArrays(event) {

                        // Since this Polygon only has one path, we can call getPath()
                        // to return the MVCArray of LatLngs
                        var vertices = this.getPath();

                        var contentString = '<b>Puntos</b><br>';
                        contentString += 'Clicked Location: <br>' + event.latLng.lat() + ',' + event.latLng.lng() + '<br>';

                        // Iterate over the vertices.
                        for (var i = 0; i < vertices.getLength() ; i++) {
                            var xy = vertices.getAt(i);
                            contentString += '<br>' + 'Coordinate: ' + i + '<br>' + xy.lat() + ',' + xy.lng();
                        }

                        // Replace our Info Window's content and position
                        infoWindow.setContent(contentString);
                        infoWindow.setPosition(event.latLng);

                        infoWindow.open(map);
                    }
                    //google.maps.event.addDomListener(window, 'load', initialize);
                    //
             

                }
                else
                {
                    function createPolygon() {}
                
                }
                var pgFn = new Object();
                pgFn.Zone    = 17;
                pgFn.HemSur  = true;
                pgFn.poinstCoords=[];//Coordenadas de poligono
                pgFn.map = null;//Mapa actual
                pgFn.myLatitudLng =null;//Punto selecionado
                pgFn.infoWindow = null;
                pgFn.render = false;//Dibuja el mapa panel inicialmente
                pgFn.editing=true;//Determina operacion grid
                pgFn.newMap = function (myLatLng) {
                    try{

                        if (typeof(google)!="undefined")
                        {
                            var myZoom=14;
                            if (myLatLng==null)
                                myLatLng = new google.maps.LatLng(-2.0929003389954786, -79.8534438490598);
                            if (pgFn.map!=null){
                                try
                                {
                                    myZoom=pgFn.map.getZoom(); //Redibujar mapa con zoom definido
                                }catch(error)
                                {
                                    myZoom=14;
                                }
                            }
                            var mapOptions = {
                                zoom:myZoom,
                                center: myLatLng,
                                mapTypeId: google.maps.MapTypeId.TERRAIN
                            };
                            pgFn.map = new google.maps.Map(document.getElementById('map-canvas'),
                               mapOptions);
                            var divBug =document.getElementById('main-frame-error');
                            divBug.setAttribute("style","display: none;");

                        }
                        else
                        {
                            
                            var divmap =document.getElementById('map-canvas');
                            divmap.setAttribute("style","display: none;");
                        }
                        }catch(jsbug){
                            AppGlobalJs.showBug("pgFn.newMap: " + jsbug)
                     }
                };
                pgFn.setPointPaint = function (arg) {
                    try{
                    if (typeof(arg) == "undefined")
                    pgFn.poinstCoords=App.gpPoinst.getRowsValues({selectedOnly : false});
                    else
                        pgFn.poinstCoords=arg;
                    createPolygon();
                    }catch(jsbug){
                        AppGlobalJs.showBug("pgFn.theEndExpediente: " + jsbug)
                    }
                }
                pgFn.selectRowPoint = function(item,selected)
                {try{
                    if (selected.length!=0)
                        if (selected[0].data.Latitud!="" &  selected[0].data.Longitud!="")
                    {
                            pgFn.myLatLng = new google.maps.Marker({
                                position: new google.maps.LatLng(selected[0].data.Latitud, selected[0].data.Longitud)
                           
                            });
                            pgFn.setPointPaint();
                    }
                    else
                    {
                        pgFn.myLatLng =null;
                    }
                  
                     #{btnRemove}.setDisabled(!selected.length);
                }catch(jsbug){
                    AppGlobalJs.showBug("pgFn.theEndExpediente: " + jsbug)
                }
                };
                //Finalizar creacion de tab expediente de metodo de aspx pgNuevo expediente
                pgFn.theEndExpediente= function (flag) {
                    try
                    {
                         if(typeof(window.parent.App.direct.EnabledTab2)!="undefined")
                         {
                                window.parent.App.direct.EnabledTab2({
                                    success: function (result) {
                                                   
                                    },
                                    eventMask: {
                                        showMask: true,
                                        minDelay: 500
                                    }
                                });
                            
                          }
                          #{hdIfCreateExp}.setValue("false");
                       

                    }catch(jsbug){
                        AppGlobalJs.showBug("pgFn.theEndExpediente: " + jsbug)
                    }
                };
                pgFn.addPoint = function (done) {
                    try
                    {
                        var grid = #{gpPoinst};
                        grid.editingPlugin.cancelEdit();
                        if (done==true)
                        {
                            // Create a record instance through the ModelManager
                            var r = Ext.ModelManager.create({
                                Latitud: '',
                                Longitud: ''
                            }, 'XY');

                            grid.store.add(r);
                            grid.editingPlugin.startEdit(r, 0);
                            pgFn.editing=false;
                            //grid.store.insert(0, r);
                            //grid.editingPlugin.startEdit(0, 0);
                        }
                    }catch(jsbug){
                        AppGlobalJs.showBug("pgFn.addBtnPoint: " + jsbug)
                    }
                };
                pgFn.addBtnPointUdate= function () {
                    try
                    {
                        pgFn.addPoint(true);
                    }catch(jsbug){
                        AppGlobalJs.showBug("pgFn.addBtnPoint: " + jsbug)
                    }
                };
                pgFn.addBtnPoint = function () {
                  try
                  {
                            var idExp = #{hdExpGeo}.getValue();
                            var done  = true;
                            //Caso de no existir idExpediente crear expediente invocado desde pgNuevoExpediente.aspx
                            if (idExp == "")
                            {
                                if(typeof(window.parent.App.btnSaveGeoRef)!="undefined")
                                {
                                   window.parent.App.btnSaveGeoRef.fireEvent('click'); 
                                   //Retorna valor de validacion de formulario 
                                   done = (window.parent.App.hdValidadForm.getValue() === 'true');
                                   if (done==true)
                                   {
                                      //Asignar valor temporar, el cual se va actualizar desde server luego de invocar metodos para 
                                      //almacenar puntos de referencia
                                      #{hdExpGeo}.setValue("ValorTemporal");
                                      #{hdIfCreateExp}.setValue(window.parent.App.hdBoolClasificacion.getValue());
                                      #{btnAdd}.hide();
                                      #{btnAddUpdate}.show();
                                   }
                                }                   
                    
                            }
                            pgFn.addPoint(done);
                           
                    }catch(jsbug){
                        AppGlobalJs.showBug("pgFn.addBtnPoint: " + jsbug)
                    }
                };
                pgFn.deleteBtnPoint = function () {
                    var grid = #{gpPoinst},
                     sm = grid.getSelectionModel();

                    grid.editingPlugin.cancelEdit();
                 
                    grid.store.remove(sm.getSelection());
                    if (grid.store.getCount() > 0) {
                        sm.select(0);
                    }
                    pgFn.setPointPaint();
                    pgFn.validarSave();
                    pgFn.myLatLng =null;
                };
             
                pgFn.resetMap = function () {
                  App.gpPoinst.editingPlugin.cancelEdit();
                  App.gpPoinst.removeAll();
                  if (App.gpPoinst.store.getCount() > 0) {
                      App.gpPoinst.getSelectionModel().select(0);
                  }
                  pgFn.newMap(null);
                  App.btnSave.disable();
                };

                pgFn.clickBtnDelete = function (record, recordIndex) {
                     App.gpPoinst.getStore().removeAt(recordIndex);                    
                     createPolygon();
                     pgFn.validarSave();
                };
                pgFn.beforeEditRow = function(editor,e){
                    if (pgFn.editing==false){
                        var recordIndex=e.rowIdx;
                        App.gpPoinst.getStore().removeAt(recordIndex);
                        pgFn.editing=true;
                    }
                };
                //Mostrar panel detalles
                pgFn.clickBtnAgregar = function (plugin) {
                    //var record = plugin.context.record;
                    //var lat    = numericFormat.toFixed(plugin.editor.form.getValues().lat,6);
                    //var log    = numericFormat.toFixed(plugin.editor.form.getValues().log, 6);
                    //if(pgFn.validarLatitud(lat))// local validation     
                    //    if(pgFn.validarLongitud(log))
                    //    {
                            pgFn.setPointPaint();
                            plugin.completeEdit();
                            pgFn.editing=true;
                        //}
                    pgFn.validarSave();
                };
                //Solo validar que almenos se ingrese un punto de referncia
                pgFn.validarSave= function () {
                    App.btnSave.disable();
                    App.btnFlag.disable();
                    if(App.gpPoinst.store.getCount()>=1)
                        App.btnSave.enable();
                    
                };
                //Permite validar la Latitud
                pgFn.validarLatitud= function(lat) 
                {
                  
                    if (lat >= -85 && lat <= 85) {
                        return true;
                    } else {
                        AppGlobalJs.showMsgError('La Latitud se comprende en números desde -85 hasta 85');
                        return false;
                    }
                    
                };
                
                //Permite validar la Longitud
                pgFn.validarLongitud=function (lon) 
                {
                    
                    if (lon >= -180 && lon <= 180) {
                        return true;
                    } else {
                        AppGlobalJs.showMsgError('La Longitud se comprende en números desde -180 hasta 180');
                       return false;
                    }
                    
                };
           </script>
    </ext:XScript>  
</body>
</html>
